<template>
    <div>
        <div class="main_operation">
            <!-- <div class="operation_left"> -->

                <!-- <a-button class="mr10" type="primary" @click="addBtn">添加</a-button>
                <a-button type="primary">导出报表</a-button> -->
            <!-- </div> -->
            <!-- <div class="operation_right">

            </div> -->
        </div>
        <a-select v-model="state" class="mr5" @change="onSearch" style="width: 100px">
          <a-select-option :value="0">全部</a-select-option>
          <a-select-option :value="1">已支付</a-select-option>
          <a-select-option :value="2">待支付</a-select-option>
          <a-select-option :value="3">待续费</a-select-option>
        </a-select>
        <a-input placeholder="请输入公司名称" style="width: 200px;margin-right:5px" v-model="formList.company_name" />
        <a-select allowClear class="mr5" style="width: 200px" v-model="formList.equipment_id" placeholder="设备名称">
            <a-select-option v-for="item in equipmentData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
        </a-select>
        <a-select allowClear class="mr5" style="width: 120px" v-model="formList.pay_type" placeholder="支付方式">
            <a-select-option :value="1" >微信支付</a-select-option>
            <a-select-option :value="2">线上支付</a-select-option>
        </a-select>
        <a-range-picker v-model="rangePickerVal" style="width: 220px" class="mr5" @change="onDateChange" />
        <a-button class="mr10" type="primary" @click="()=>{formList.page = 1;changeData()}">搜索</a-button>
        <a-button type="danger" @click="Reset">重置</a-button>
        <div class="mt10 main">
            <a-table bordered :pagination="false" :loading="tableLoad" :columns="Fields" :dataSource="dataLists.data" :rowKey="record => record.id" :scroll="{x:1150, y: 600 }">
                >
                <template slot="equipment_name" slot-scope="text, record">
                    <a style="color: #0000cc;" href="javascript:void(0);" @click="onName(record)">{{text}}</a>
                </template>
                <template slot="action" slot-scope="text, record">
                    <template>
                        <a-button v-if="isAdmin || routerShow($route,'order_offline')" type="primary" class="btn-info mb5" size="small" @click="payment(record, 1)">平台开通</a-button>
                        <a-button v-if="record.pay_status  == 2" class="btn-success" type="primary" size="small" @click="payment(record, 2)">微信支付</a-button>
                        <a-button v-else type="primary" class="btn-error" size="small" @click="payment(record, 3)">线上续费</a-button>
                        <!-- <a-button v-if="record.invoice_id == null && record.pay_status == 1" type="primary" class="mt5" size="small" @click="invoiceBtn(record)">开票申请</a-button>
                        <a-button v-if="record.invoice_id != null && record.pay_status == 1" disabled type="primary" class="mt5" size="small">发票已申请</a-button> -->
                    </template>
                </template>
            </a-table>
            <div class="pageBox">
                <a-pagination :total="dataLists.total" :showTotal="total => `共 ${total} 条数据`" :pageSize="dataLists.per_page" :defaultCurrent="1" @change="pageChange" />
            </div>
        </div>
        <!-- 支付窗口 -->
        <a-modal :maskClosable="false" :destroyOnClose="true" :title="titleModel" v-model="visible">
            <template slot="footer">
                <a-button key="back" @click="handleCancel">取消</a-button>
                <a-button key="submit" type="primary" :loading="confirmLoading" @click="handleOk">
                    {{titleModel == '平台开通'? '确认开通' : titleModel == '微信支付' ? '确定' : '确认续费' }}
                </a-button>
            </template>
            <a-form>
                <a-form-item v-if="listitemData.expire_time" label="设备到期时间:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    当前设备将于<span class="col-red">{{listitemData.expire_time}}</span>到期！
                </a-form-item>
                <a-form-item label="公司名称:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    {{listitemData.company_name}}
                </a-form-item>
                <a-form-item label="设备名称:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    {{listitemData.equipment_name}}
                </a-form-item>
                <a-form-item required label="套餐名称:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-select @change="setMealChange" v-model="formItem.set_meal_id" placeholder="请选择套餐">
                        <a-select-option v-for="(item,i) in setMealAllData" :value="item.id" :key="item.id">
                            {{item.title}}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="账号数量:" v-if="formItem.set_meal_id" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    {{mealDetails.account_num}}个
                </a-form-item>
                <a-form-item required label="缴费时长:" v-if="formItem.set_meal_id" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-radio-group @change="radioChange" buttonStyle="solid">
                        <a-radio-button class="mr10 mb10" v-for="(item,i) in mealDetails.item" :key="item.id" :value="item">
                            <ul>
                                <!-- <li style="border-bottom: 1px solid #d9d9d9;">{{item.duration}}{{item.date_unit == 1 ? '个月' : '年'}}</li> -->
                                <li>
                                  ￥{{item.cost}}元/{{item.duration}}{{item.date_unit == 1 ? '个月' : '年'}} 
                                  <s style="color: #aaa;fontSize: 14px;">{{item.price}}元/{{item.duration}}{{item.date_unit == 1 ? '个月' : '年'}}</s>
                                </li>
                            </ul>
                        </a-radio-button>
                    </a-radio-group>
                </a-form-item>
                <a-form-item :label-col="{ md: 0,xs:0 }" :wrapper-col="{ md: 23,xs:23 }">
                    <p style="text-align: right;">
                        应付金额:
                        <span style="color: #ed4e37;fontSize: 20px;">{{mealTimeDetails.cost ? mealTimeDetails.cost: 0 }}</span>元&nbsp;
                        <s style="color: #aaa;fontSize: 14px;">原价:{{mealTimeDetails.price ? mealTimeDetails.price: 0 }}元</s>
                    </p>

                </a-form-item>
            </a-form>
            <!-- <p class="tac mb10" v-if="formItem.set_meal_id">缴费信息：套餐{{mealDetails.set_meal_fee}}元/年,用户{{mealDetails.account_fee}}元/年/人。</p> -->
            <!-- <template v-if="titleModel == '线下支付'">
        <ul class="account">
          <li>
            <a-input-group compact>
              <div style="width: 20%; vertical-align: middle">收款户名: </div>
              <a-input style="width: 70%; margin-right: 10px; vertical-align: middle" v-model="formItem.receivable_name" placeholder="请输入收款户名" />
            </a-input-group>
            </li>
          <li>
            <a-input-group compact>
              <div style="width: 20%; vertical-align: middle">收款帐号: </div>
              <a-input style="width: 70%; margin-right: 10px; vertical-align: middle" v-model="formItem.receivable_account" placeholder="请输入收款帐号" />
            </a-input-group>
          </li>
          <li>
            <a-input-group compact>
              <div style="width: 20%; vertical-align: middle">开户银行: </div>
              <a-input style="width: 70%; margin-right: 10px; vertical-align: middle" v-model="formItem.bank_name" placeholder="请输入开户银行" />
            </a-input-group>
          </li>
        </ul>
        <p class="tac mt10" style="font-size: 14px;">确认收到款项后,管理员将为您立即开通。</p>
      </template> -->
        </a-modal>
        <a-modal title="请使用微信扫一扫并支付" destroyOnClose :maskClosable="false" :footer='null' v-model="weChatCodeModel" @cancel="weChatCodeCancel">
            <div style="text-align: center;">
                <h2>{{mealDetails.title}}</h2>
                <div v-if="weChatCodeShow" v-html="weChatCode"></div>
                <div v-else class="mb10">
                    <a-icon class="mt10 mb10" title="支付成功" theme="filled" style="fontSize: 90px;  color: #52c41a;" type="check-circle" />
                    <p>支付成功</p>
                </div>
                <div>￥<span style="color: #ed4e37;">{{mealTimeDetails.cost ? mealTimeDetails.cost: 0 }}</span>元</div>
            </div>
        </a-modal>
        <a-modal title="开票申请" :width="600" :maskClosable="false" destroyOnClose v-model="invoiceModel" @ok="invoiceOk" :confirmLoading="confirmLoading" @cancel="invoiceCancel">
            <a-form>
                <h3 class="modelTitle">发票信息</h3>
                <a-form-item required label="发票类型:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-select v-model="invoiceForm.invoices_type">
                        <a-select-option value="ordinary">普票</a-select-option>
                        <a-select-option value="special">专票</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="抬头:" required :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="invoiceForm.invoices_name" placeholder="请输入发票抬头" />
                </a-form-item>
                <a-form-item required label="纳税人识别号:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="invoiceForm.identification" placeholder="请输入纳税人识别号" />
                </a-form-item>
                <template v-if="invoiceForm.invoices_type == 'special'">
                    <a-form-item required label="注册电话:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                        <a-input v-model="invoiceForm.telephone" placeholder="请输入注册电话" />
                    </a-form-item>
                    <a-form-item required label="开户银行:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                        <a-input v-model="invoiceForm.bank_name" placeholder="请输入开户银行" />
                    </a-form-item>
                    <a-form-item required label="银行帐户:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                        <a-input v-model="invoiceForm.bank_account" placeholder="请输入银行帐户" />
                    </a-form-item>
                </template>
                <h3 class="modelTitle">快递信息</h3>
                <a-form-item required label="收件人:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="invoiceForm.name" placeholder="请输入收件人" />
                </a-form-item>
                <a-form-item required label="所在地区:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-cascader v-model="RegionName" :options="RegionData" @change="onRegionChange" :fieldNames="{ label: 'name', value: 'name', children: 'children' }" placeholder="请选择所在地区" />
                </a-form-item>
                <a-form-item required label="详细地址:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="invoiceForm.address" placeholder="请输入详细地址" />
                </a-form-item>
                <a-form-item required label="联系电话:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="invoiceForm.mobile" placeholder="请输入联系电话" />
                </a-form-item>
                <a-form-item label="邮政编号:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-input v-model="invoiceForm.zip" placeholder="请输入邮政编号" />
                </a-form-item>
            </a-form>
        </a-modal>
        <!-- 订单添加 -->
        <a-modal title="添加订单" destroyOnClose :maskClosable="false" v-model="addModel" @ok="addOk">
            <a-form>
                <a-form-item required label="所属用户:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-select v-model="addOrderForm.user_id" @change="userIdChange">
                        <a-select-option v-for="item in orderAccountData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="用户设备:" required :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
                    <a-select v-model="addOrderForm.equipment_id">
                        <a-select-option v-for="item in userEquipmentData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
import {
  mapState,
  mapActions,
} from 'vuex';
import Vue from 'vue';
import {
  USER,
} from '@/store/mutation-types';

export default {
  name: 'Recharge',
  data() {
    return {
      timer: '', // 定时器
      weChatCodeShow: true, // 二维码显示
      weChatCodeModel: false, // 微信扫码
      /* 添加订单 */
      addModel: false, // 添加订单窗口
      addOrderForm: {
        // user_id: undefined,
        // equipment_id: undefined,
      },
      userEquipmentData: [],
      /* 添加订单end */

      isAdmin: false, // 是否后台管理猿
      invoiceModel: false, // 开票
      RegionName: [], // 地区
      invoiceForm: {
        // oid: '',
        // user_id: '',
        // invoices_type: 'ordinary',
        // invoices_name: '',
        // identification: '',
        // name: '',
        // area: '',
        // address: '',
        // mobile: '',
        // zip: '',
      },
      /* 通用模块 */
      // 列表
      tableLoad: false, // 列表loading状态
      state: 0,
      rangePickerVal: undefined,
      formList: {
        // 列表信息
        company_name: '',
        pay_type: undefined,
        state: '',
        page: 1,
      },
      /* 通用模块end */

      /* 支付 */
      titleModel: '', // 标题
      visible: false, // 窗口显示隐藏
      confirmLoading: false, // 按钮loading状态
      formItem: {
        oid: '', // 订单ID
        set_meal_id: undefined, // 套餐ID
        set_meal_item_id: '', // 缴费时长
      },
      /* 支付 */
      listitemData: {}, // 当前行设备信息
      mealDetails: {}, // 套餐信息
      mealTimeDetails: {}, // 套餐时长信息
      userData: {},
    };
  },
  computed: {
    ...mapState({
      Fields: state => state.paymentRecharge.Fields,
      dataLists: state => state.paymentRecharge.dataLists,
      requestCode: state => state.paymentRecharge.requestCode,
      weChatCode: state => state.paymentRecharge.weChatCode, // 支付二维码
      RegionData: state => state.paymentRecharge.RegionData,

      setMealAllData: state => state.paymentAccount.setMealAllData, // 套餐信息
      orderAccountData: state => state.paymentRecharge.orderAccountData, // 添加订单用户id
      // userEquipmentData: state => state.paymentRecharge.userEquipmentData,// 用户id查设备
      equipmentData: state => state.equipment.equipmentData, // 设备名称信息

    }),
  },
  mounted() {
    this.userData = Vue.ls.get(USER);
    if (this.userData.role_grade === 1) {
      this.isAdmin = true;
    } else {
      this.isAdmin = false;
    }
    this.equipmentAll();
    this.changeData();
    this.region();
    this.orderAccount();
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前，清除定时器
    }
  },
  methods: {
    // 搜索重置
    Reset() {
      this.state = 0;
      this.rangePickerVal = undefined;
      this.formList = {
        // 列表信息
        company_name: '',
        pay_type: undefined,
        state: '',
        created_start: '',
        created_end: '',
        pay_status: '',
        page: 1,
      },
      this.changeData();
    },
    // 日期
    onDateChange(date, dateStrings) {
      console.log(date, dateStrings);
      this.formList.created_start = dateStrings[0];
      this.formList.created_end = dateStrings[1];
      if (!date.length) {
        delete this.formList.created_start;
        delete this.formList.created_end;
      }
    },
    onName(item) {
      this.$router.push({
        path: `/payment/payRecord/${item.equipment_id}`,
      });
    },
    // add获取用户设备
    userIdChange(val) {
      console.log(val);
      const arr = {
        user_id: val,
      };
      this.getUserEquipment(arr)
        .then((res) => {
          console.log(res);
          if (res.data.errorCode === 0) {
            this.userEquipmentData = res.data.result;
          }
          // this.userEquipment
          // commit("setErrorCode", response.data.errorCode);
        });
    },
    addOk() {
      console.log(this.addOrderForm);
      // this.confirmLoading = true;
      this.dataAdd(this.addOrderForm);
      setTimeout(() => {
        if (this.requestCode === 0) {
          this.addModel = false;
          this.changeData();
        }
        // this.confirmLoading = false;
      }, 1000);
    },
    // 添加订单
    addBtn() {
      this.addModel = true;
    },
    // 地区选择
    onRegionChange(value, selectedOptions) {
      this.invoiceForm.area = value.join(' ');
      console.log(this.invoiceForm);
    },
    // 开票按钮
    invoiceBtn(item) {
      console.log(item);
      this.RegionName = [];
      this.invoiceForm = {
        oid: item.oid,
        user_id: item.user_id,
        invoices_type: 'ordinary',
        invoices_name: '',
        identification: '',
        name: '',
        area: '',
        address: '',
        mobile: '',
        zip: '',
      },
      this.invoiceModel = true;
    },
    // 确定开票
    invoiceOk() {
      // console.log(this.invoiceForm);
      this.confirmLoading = false;
      this.invoice(this.invoiceForm);
      setTimeout(() => {
        // console.log(this.requestCode);
        if (this.requestCode === 0) {
          this.invoiceModel = false;
          this.changeData();
        }
        this.confirmLoading = false;
      }, 1000);
      this.invoiceModel = false;
    },
    invoiceCancel() {
      this.invoiceModel = false;
    },
    /* 通用模块 */
    /* 接口 */
    ...mapActions({
      getLists: 'paymentRecharge/getLists', // 订单列表
      dataAdd: 'paymentRecharge/dataAdd', // 订单添加
      orderAccount: 'paymentRecharge/orderAccount', // 订单添加用户信息
      getUserEquipment: 'paymentRecharge/getUserEquipment', // 用户查设备
      paymentDetail: 'paymentRecharge/paymentDetail', // 查询订单支付状态

      weChatPayment: 'paymentRecharge/weChatPayment', // 微信支付
      offlinePay: 'paymentRecharge/offlinePay', // 微信支付
      invoice: 'paymentRecharge/invoice', // 开票
      region: 'paymentRecharge/region', // 城市联动
      orderOpening: 'paymentRecharge/orderOpening', // 平台确认开通
      setMealAll: 'paymentAccount/setMealAll', // 套餐信息
      equipmentAll: 'equipment/equipmentAll', // 设备名称信息

    }),
    // 勾选
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    // 重新获取列表数据
    changeData() {
      this.tableLoad = true;
      setTimeout(() => {
        this.getLists(this.formList);
        this.tableLoad = false;
      }, 1000);
    },
    // 搜索
    onSearch(val) {
      console.log(val);
      if (val == 0) {
        this.formList.pay_status == '';
      } else {
        this.formList.pay_status = val;
      }
    //   this.formList.page = 1;
    //   this.changeData();
    },
    // 页码
    pageChange(page) {
      this.formList.page = page;
      this.getLists(this.formList);
    },
    /* 通用模块end */

    /* 支付 */
    // 套餐选择
    setMealChange(val) {
      this.mealTimeDetails = {};
      console.log(this.setMealAllData);
      this.setMealAllData.map((item) => {
        if (val == item.id) {
          this.mealDetails = item;
        }
      });
    },
    // 套餐选择时长
    radioChange(e) {
      console.log(e);
      this.mealTimeDetails = e.target.value;
    },
    // 支付按钮
    payment(item, type) {
      // if(type == 3){
      //   this.$warning({
      //     title: '续费功能未上线',
      //     content: '续费功能未上线',
      //   });
      //   return null
      // }
      this.setMealAll({
        id: item.id,
      });
      console.log(item);
      this.listitemData = item;
      this.mealDetails = {};
      this.mealTimeDetails = {};
      // console.log(type);
      if (type == 1) {
        this.titleModel = '平台开通';
        this.formItem = {
          oid: item.oid, // 订单ID
          set_meal_id: undefined, // 套餐ID
          set_meal_item_id: '', // 缴费时长
        };
      } else if (type == 2) {
        this.titleModel = '微信支付';
        this.formItem = {
          oid: item.oid, // 订单ID
          set_meal_id: undefined, // 套餐ID
          set_meal_item_id: '', // 缴费时长
        };
      } else if (type == 3) {
        this.titleModel = '续费';
        this.formItem = {
          oid: item.oid, // 订单ID
          set_meal_id: undefined, // 套餐ID
          set_meal_item_id: '', // 缴费时长
        };
      }
      this.visible = true;
    },
    // 窗口确定
    handleOk() {
      this.confirmLoading = true;
      this.formItem.set_meal_item_id = this.mealTimeDetails.id;
      if (this.titleModel == '微信支付' || this.titleModel == '续费') {
        this.weChatPayment(this.formItem);
      } else if (this.titleModel == '平台开通') {
        this.offlinePay(this.formItem);
      }
      setTimeout(() => {
        if (this.requestCode === 0) {
          if (this.titleModel == '微信支付' || this.titleModel == '续费') {
            this.visible = false;
            this.weChatCodeModel = true;
            this.weChatCodeShow = true;
            this.timer = setInterval(() => {
              this.paymentDetail(this.formItem.oid).then((response) => {
                // console.log(response);
                if (response.data.errorCode === 0) {
                  if (response.data.result.trade_state == 'SUCCESS') {
                    this.weChatCodeShow = false;
                    this.weChatCodeCancel();
                  }
                }
              }).catch((error) => {
                console.log(error);
              });
            }, 4000);
          } else {
            this.visible = false;
            this.changeData();
          }
        }
        this.confirmLoading = false;
      }, 1000);
    },
    weChatCodeCancel() {
      if (this.timer) {
        clearInterval(this.timer);
        this.changeData();
      }
    },
    // 窗口取消
    handleCancel() {
      this.visible = false;
    },
    /* 支付end */
  },
};
</script>

<style scoped>
.account {
    text-align: center;
    /* background: #d7d7d7; */
    font-weight: bold;
    font-size: 18px;
}

.account li {
    margin-bottom: 10px;
}

.modelTitle {
    font-weight: bold;
    margin: 0 10px 10px;
    padding-left: 10px;
    padding-bottom: 5px;
    border-bottom: 1px solid #ddd;
}

>>>.ant-radio-group .ant-radio-button-wrapper {
    width: 100%;
    height: auto;
    padding: 0;
}

>>>.ant-radio-group .ant-radio-button-wrapper ul {
    width: 100%;
    box-sizing: border-box;
    text-align: center;
    padding: 8px 15px;
    font-size: 18px;
    color: darkorange;
}
</style>
